package com.jia.file.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jia.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileController {

    @Autowired
    FileService fileService;

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/file/upload")
    public Map<String,Object> upload(MultipartFile file, HttpServletRequest req) throws FileNotFoundException {
        HashMap<String, Object> result = new HashMap<>();
        String originalName = file.getOriginalFilename();
        String format = sdf.format(new Date());
        String realPath = req.getServletContext().getRealPath("/") + format; //项目当前的路径
        // String realPath = ResourceUtils.getURL("classpath:").getPath() + "static" +format;
        File folder = new File(realPath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString()+originalName;
        try {
            file.transferTo(new File(folder,newName));
            String url = req.getScheme() + "://"+req.getServerName()+":"+req.getServerPort() + format + newName;
            result.put("success",true);
            result.put("status",200);
            result.put("code",0);
            result.put("msg","上传成功");
            result.put("url",url);
            com.jia.file.entity.File myFile = new com.jia.file.entity.File();
            myFile.setUrl(url);
            myFile.setFilename(originalName);
            fileService.save(myFile);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success",false);
            result.put("code",1);
            result.put("status",400);
            result.put("msg","上传失败");
        }
        return result;
    }

    @GetMapping("/file/list")
    public Map<String,Object> list(@RequestParam long pageNum, @RequestParam long pageSize) {
        Map<String,Object> map =  fileService.getPageList(pageNum,pageSize);
        return map;
    }

}
